<?php

namespace app\order\logic;

use app\common\service\CommonExportCsvTaskLogService;
use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\order\model\OrderSourceModel;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Db;
use think\facade\Cache;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;
use app\api\logic\ApiAdvLogic;

class OrderSourceLogic extends BasicLogic
{
    public function __construct()
    {
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $limit = $params['limit'] ?? 10;
        $page  = $params['page'] ?? 1;

        $where = $this->buildTableParames($params);
        $shop_id = $params['shop_id']??'17';
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $order = ['createtime' => 'desc'];
        $lists = Db::name('order_source')
            ->field('id,name,total_price,financial_status,created_at,status,firstVisit_source,firstVisit_campaign,lastVisit_source,lastVisit_campaign,first_source,first_campaign,last_source,last_campaign,tag_source,tag_campaign,landing_site,tags,skus')
            ->where($where)
            ->where('shop_id',$shop_id)
            ->order($order)
            ->limit(($page - 1) * $limit, $limit)
            ->select();

        $lists = objectToArray($lists);
        $count =  Db::name('order_source')->where($where)->where('shop_id',$shop_id)->count();

        $data = [
            'list'  => $lists,
            'total' => $count,
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 运营标签列表
     * @author zhangheng
     */
    public function OperationLabelList($params = [])
    {
        $data = $this->arr_campaign(2);
        return json(DefaultResponse(200, true, '获取成功', $data));
    }
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 渠道标签列表
     * @author zhangheng
     */
    public function ChannelLabelList($params = [])
    {
        $data = $this->arr_source();
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function export($params = [])
    {
        $shop_id = $params['shop_id']??'17';
        $where = $this->buildTableParames($params);
        $count =  Db::name('order_source')->where($where)->where('shop_id',$shop_id)->count();
        
        if(empty($where)){
            self::export_now($params);
            return json(DefaultResponse(200, true, '操作成功', null));
        }else{
            if($count >200){
                //异步导出
                self::export_sync($params);
                $message = "数据超过2000条,异步下载中，请2分钟后前往【任务组管理/系统导出管理】页面下载";
                return json(DefaultResponse(200, true, $message, null));
            }else{
                return self::export_now($params);
            }
        }

    }



    /**
     * @desc    获取导出总数
     * @date    2024-08-15
     * @author  luckyXiong
     */
    public function getExportCount($params){
        $shop_id = $params['shop_id']??'17';
        $createtime  = $params['createtime'];
        if(empty($createtime)){
            return json(DefaultResponse(201, true, '请输入筛选时间'));
        }
        
        $where = $this->buildTableParames($params);
        $count =  Db::name('order_source')->where($where)->where('shop_id',$shop_id)->count();
        return json(DefaultResponse(200, true, '获取成功', $count));
    }





    /**
     * @desc   同步导出数据
     * @author xx
     * @date   2024-08-12
     */
    public function export_now($params){
        $shop_id = $params['shop_id']??'17';
        $header = [];
        $header[] = ['日期', 'created_at'];
        $header[] = ['订单号', 'name'];
        $header[] = ['支付状态', 'financial_status'];
        $header[] = ['物流状态', 'fulfillment_status'];
        $header[] = ['原销售额$', 'old_total_price'];
        $header[] = ['退款$', 'refund_price'];
        $header[] = ['现销售额$', 'total_price'];
        $header[] = ['账单物流费$', 'freight'];
        $header[] = ['预估物流费$(仅参考)', 'estimate_freight'];
        $header[] = ['采购成本$', 'material'];
        $header[] = ['争议金$', 'dispute'];
        $header[] = ['美金汇率', 'dollar'];
        $header[] = ['币种', 'currency'];
        $header[] = ['tag_source', 'tag_source'];
        $header[] = ['tag_campaign', 'tag_campaign'];
        $header[] = ['原记录标签', 'tags'];
        $header[] = ['landing_site', 'landing_site'];
        $header[] = ['物流匹配状态', 'freight_status'];
        $header[] = ['采购匹配状态', 'material_status'];
        $header[] = ['争议类型', 'disputeapi_type'];
        $header[] = ['争议状态', 'disputeapi_status'];
        $header[] = ['总件数', 'skuquantity'];
        $header[] = ['SKU', 'sku'];
        $header[] = ['firstVisit_source', 'firstVisit_source'];
        $header[] = ['firstVisit_campaign', 'firstVisit_campaign'];
        $header[] = ['lastVisit_source', 'lastVisit_source'];
        $header[] = ['lastVisit_campaign', 'lastVisit_campaign'];
        $header[] = ['last_source', 'last_source'];
        $header[] = ['last_campaign', 'last_campaign'];
        $header[] = ['first_source', 'first_source'];
        $header[] = ['first_campaign', 'first_campaign'];

        $tableName = "OrderSource";

        $createtime = $params['createtime'] ?? "";
        if (!empty($createtime)) {
            $where[] = ['a.createtime', '>=', strtotime($createtime['0'])];
            $where[] = ['a.createtime', '<=', strtotime($createtime['1']) + 3600*24-1];

            //汇率
            $date = date('Y-m', strtotime($createtime['0']));
        }else{
            $yesterday = strtotime(date('Y-m-d', strtotime('-1 day') - timezone()));
            $where[] = ['a.createtime', '>=', $yesterday];
            $where[] = ['a.createtime', '<=', $yesterday + 3600*24-1];

            //汇率
            $date = date('Y-m', strtotime('-32 day'));
        }

        $where_total_price[]  = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

        //新增条件
        $tag_campaign = $params['tag_campaign'] ?? "";
        $tag_source = $params['tag_source'] ?? "";

        if (!empty($tag_campaign)) {
            $where[] = array('a.tag_campaign', '=', $tag_campaign);
        }
        if (!empty($tag_source)) {
            $where[] = array('a.tag_source', '=', $tag_source);
        }

        //汇率
        $order_exchange = Db::name('order_exchange')
            ->where(['date' => $date])
            ->find();

        if (empty($order_exchange)) {
            $order_exchange = Db::name('order_exchange')
                ->order('id desc')
                ->find();
        }
        $lists = Db::name('order_source')
            ->field('
                a.id,
                a.name,
                a.total_price,
                a.financial_status,
                a.created_at,
                a.status,
                a.firstVisit_source,
                a.firstVisit_campaign,
                a.lastVisit_source,
                a.lastVisit_campaign,
                a.first_source,
                a.first_campaign,
                a.last_source,
                a.last_campaign,
                a.tag_source,
                a.tag_campaign,
                a.landing_site,
                a.tags,
                a.skus,
                a.shop_id,
                b.estimate_freight,
                b.freight,
                b.material,
                b.dispute,
                b.old_total_price,
                b.skuquantity,
                b.refund,
                b.freight_status,
                b.material_status,
                b.disputeapi_type,
                b.disputeapi_status,
                b.sku,
                b.currency
            ')
            ->alias('a')
            ->join('qu_order_achievement b','b.order_id = a.order_id', 'left')
            ->where($where)
            ->where($where_total_price)
            ->where('a.shop_id',$shop_id)
            ->select()
            ->toArray();
            // halt($lists);
        foreach ($lists as $k=>$v) {
            //填充预估物流费
            if($v['freight'] <= 0.001){
                $v['freight'] = $v['estimate_freight'] ?? 0;
            }
            if(empty($v['fulfillment_status'])){
                $lists[$k]['fulfillment_status'] = "未发货";
            }
            $lists[$k]['tag_source'] = $this->tag_source($v['tag_source']);
            $lists[$k]['tag_campaign'] = $this->tag_campaign($v['tag_campaign']);
            //物流--人民币转美金
            if((float)$v['freight'] > 0){
                $lists[$k]['freight']  = (float)number_format((float)$v['freight'] / $order_exchange['dollar'], 3, '.', '');
            }
            if((float)$v['estimate_freight'] > 0){
                $lists[$k]['estimate_freight']  = (float)number_format((float)$v['estimate_freight'] / $order_exchange['dollar'], 3, '.', '');
            }
            //采购
            if((float)$v['material'] > 0){
                $lists[$k]['material'] = (float)number_format((float)$v['material'] / $order_exchange['dollar'], 3, '.', '');
            }
            $lists[$k]['dollar']   = $order_exchange['dollar'];
            if(!$v['old_total_price'] && !$v['total_price']){
                $lists[$k]['refund_price']  = '0.00';
            }else{
                $lists[$k]['refund_price']   =  $v['old_total_price']-$v['total_price'];
            }
        }

        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }


    /**
     * @desc   异步导出数据
     * @author xx
     * @date   2024-08-12
     */
    public function export_sync($params=[]){
        try{
            $params['limit']   = 2000;
            $export_type       = $params['export_type']??'';
            $csvTaskLogService = new CommonExportCsvTaskLogService();
            $exportResult = $csvTaskLogService->operate_export_follow_data([
                new OrderSourceModel(),
                $params,
                CommonExportCsvTaskLogService::SHOPIFY_SOURCE_MONTH_EXPORT,
                $this,
                get_class($this)
            ]);
            if(empty($exportResult['status'])) {
                return $this->jsonMessage(201, false, $exportResult, null);
            }
        }catch (\Exception $e){
            return $this->jsonMessage(201, false, $e->getMessage(), null);
        }

        if($export_type=='downLoad'){
            return  ['msg'=>'导出成功','info'=>$exportResult];
        }else{
            return  ['msg'=>'操作成功,异步导出需要一段时间处理','info'=>null];
        }
    }











    /**
    * @desc    编辑
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function edit($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $result = false;

        try {
            
            foreach ($data as $value) {
                $updateData = [
                    'tag_source' => !empty($value["tag_source"]) ? $value["tag_source"] : "other",
                    'tag_campaign' => !empty($value["tag_campaign"]) ? $value["tag_campaign"] : "LabelIsEmpty",
                    'status' => 3,
                ];
                if($updateData['tag_source'] == "直接访问" || $updateData['tag_source'] == "email" || $updateData['tag_source'] == "other"){
                    $updateData['tag_campaign'] = "LabelIsEmpty";
                }
                if($updateData['tag_source'] == "LabelIsEmpty"){
                    $updateData['tag_source'] = "other";
                }
                table('order_source')
                    ->where('id', $value['id'])
                    ->update($updateData);
            }

            $result = true;
            
            if ($result) {
                return json(DefaultResponse(200, false, '更新成功!', null));
            }
            return json(DefaultResponse(201, false, '更新失败!', null));
        } catch (ValidateException $e) {
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            return json(DefaultResponse(201, false, '更新失败!', null));
        }
        return json(DefaultResponse(200, false, '更新成功!', null));
    }
    
    /**
    * @desc    构建where
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function buildTableParames($params)
    {
        $keyword = $params['keyword'] ?? "";
        $createtime = $params['createtime'] ?? "";
        $order_id = $params['order_id'] ?? "";
        $sku = $params['sku'] ?? "";
        $tag_campaign = $params['tag_campaign'] ?? "";
        $status = $params['status'] ?? "";
        $tag_source = $params['tag_source'] ?? "";

        $where = [];


        if (!empty($order_id)) {
            $order_ids = explode("\n", trim($order_id));
            $order_ids_new = array_map('trim', array_filter($order_ids, function($v) {  
                return !empty(trim($v));  
            }));
            if (!empty($order_ids_new)) {
                $where[] = ['order_id|name|order_number', 'in', $order_ids_new];
            }
        }

        if (!empty($sku)) {
            $where[] = array('sku', 'LIKE', '%' . trim($sku) . '%');
        }
        if (!empty($tag_campaign)) {
            $where[] = array('tag_campaign', '=', $tag_campaign);
        }
        if (!empty($tag_source)) {
            $where[] = array('tag_source', '=', $tag_source);
        }
        if (!empty($keyword)) {
            $keyword = '%' . $keyword . '%';
            $where[] = ['
                order_number|
                first_source|
                first_campaign|
                last_source|
                last_campaign|
                firstVisit_campaign|
                firstVisit_source|
                lastVisit_campaign|
                lastVisit_source|
                landing_site', 'like', $keyword
            ];
        }

        if (!empty($status)) {
            switch ($status) {
                case 'matched':
                    $where[] = array('status', '=',1);
                    break;
                case 'matching_failed':
                    $where[] = array('status', '=',2);
                    break;
                case 'manually_modifying':
                    $where[] = array('status', '=',3);
                    break;
                case 'unmatched':
                    $where[] = array('status', '=',0);
                    break;
                case 'fb':
                    $where[] = array('tag_source', '=', 'fb');
                    break;
                case 'tt':
                    $where[] = array('tag_source', '=', 'tt');
                    break;
                case 'ggad':
                    $where[] = array('tag_source', '=', 'ggad');
                    break;
                case 'email':
                    $where[] = array('tag_source', '=', 'email');
                    break;
                case 'other':
                    $where[] = array('tag_source', '=', 'other');
                    break;
                case 'direct_access':
                    $where[] = array('tag_source', '=', '直接访问');
                    break;
                case '待确认':
                    $where[] = array('tag_source', '=', '待确认');
                    break;
                case 'AllianceInternetCelebrity':
                    $where[] = array('tag_source', '=', 'impact');
                    break;
                default:
            }
        }


        $date = $params['date'] ?? "";
        if($date){
            $where[] = ['createtime', '>=', strtotime($date)];
            $endtime = strtotime('+1 month -1 day', strtotime($date));
            $where[] = ['createtime', '<=', $endtime + 3600*24-1];
            return $where;
        }

        if (!empty($createtime)) {
            $where[] = ['createtime', '>=', strtotime($createtime['0'])];
            $where[] = ['createtime', '<=', strtotime($createtime['1']) + 3600*24-1];
        }
        return $where;
    }
    
    /**
    * @desc    按渠道查看销售业绩
    * @date    2024/7/22
    * @author  zhangheng
    */
    public function SalesPerformanceChannel($params = [])
    {
        $where = $this->buildTableParames($params);

        $where_total_price[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $shop_id = $params['shop_id']??'17';
        $lists = Db::name('order_source')
            ->field('COUNT(id) as count,sum(total_price) as total_price,tag_source,tag_campaign')
            ->where($where)
            ->where($where_total_price)
            ->where('shop_id',$shop_id)
            ->group('tag_source,tag_campaign')
            ->order('tag_source desc,tag_campaign desc')
            ->select()
            ->toArray();
        $lists_news = array();
        if(!empty($lists)){
            $groupedStatistics = [];
            $totalPrices = 0;
            foreach ($lists as $item) {
                $tagSource = $item["tag_source"];
                $totalPrice = $item["total_price"];
                $totalPrices += $item["total_price"];
                $totalCount = $item["count"];
                if (!empty($tagSource) && is_numeric($totalPrice)) {
                    if (!array_key_exists($tagSource, $groupedStatistics)) {
                        $groupedStatistics[$tagSource] = ["total_price_sum" => 0,"count" => 0, "children" => []];
                    }
                    $groupedStatistics[$tagSource]["total_price_sum"] += $totalPrice;
                    $groupedStatistics[$tagSource]["count"] += $totalCount;
                    if (!in_array($tagSource, $groupedStatistics[$tagSource]["children"])) {
                        $groupedStatistics[$tagSource]["children"][] = $item;
                    }
                }
            }
            if($totalPrices == 0){
                return json(DefaultResponse(200, true, '暂无数据', []));
            }
            //统计
            foreach ($groupedStatistics as $k => $v) {
                foreach ($v['children'] as &$vc) {
                    $vc['proportion'] = number_format((float)$vc['total_price']/$v['total_price_sum']*100, 2, '.', '')."%";
                }
                array_multisort(array_column($v['children'], 'total_price'), SORT_DESC, $v['children']);
                $lists_new = array(
                    'total_price' => number_format((float)$v['total_price_sum']*1, 2, '.', ''),
                    'proportion' => number_format((float)$v['total_price_sum']/$totalPrices*100, 2, '.', '')."%",
                    'prominent' => 1,
                    'count' => $v['count'],
                    'tag_source' => $k,
                    'tag_campaign' => "统计",
                    'children' => $v['children'],
                );
                $lists_news[] = $lists_new;
            }
            //lists_news按total_price最大的排序
            array_multisort(array_column($lists_news, 'total_price'), SORT_DESC, $lists_news);
        }
        
        return json(DefaultResponse(200, true, '获取成功', $lists_news));
    }

    /**
    * @desc    按sku查看销售业绩
    * @date    2024/7/22
    * @author  zhangheng
    */
    public function SalesPerformanceSku($params = [])
    {
        if (empty($params['createtime']) && empty($params['date'])) {
            return json(DefaultResponse(201, false, '请添加搜索日期'));
        }
        $where = $this->buildTableParames($params);
        $shop_id = $params['shop_id']??'17';
        $where_total_price[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

        $lists = Db::name('order_source')
            ->field('total_price,tag_campaign,skus')
            ->where($where)
            ->where($where_total_price)
            ->where('shop_id',$shop_id)
            ->order('tag_campaign desc')
            ->select()
            ->toArray();
            
        $lists_news = array();
        if(!empty($lists)){
            $groupedStatistics = [];
            foreach ($lists as $item) {
                $tagCampaign = $item["tag_campaign"];
                $totalPrice = $item["total_price"];
                if (!empty($tagCampaign) && is_numeric($totalPrice)) {
                    if (!array_key_exists($tagCampaign, $groupedStatistics)) {
                        $groupedStatistics[$tagCampaign] = ["total_price_sum" => 0, "children" => []];
                    }
                    $groupedStatistics[$tagCampaign]["total_price_sum"] += $totalPrice;
                    if (!in_array($tagCampaign, $groupedStatistics[$tagCampaign]["children"])) {
                        $groupedStatistics[$tagCampaign]["children"][] = $item['skus'];
                    }
                }
            }
            //统计
            foreach ($groupedStatistics as $k => $v) {
                $childrens = $this->NumberOfSKUsProcessed($v['children']);
                $lists_new = array(
                    'spu' => "统计",
                    'tag_campaign' => $k,
                    'count' => $childrens['count'],
                    'total_price' => number_format((float)$v['total_price_sum']*1, 2, '.', ''),
                    'children' => $childrens['childrens'],
                );
                $lists_news[] = $lists_new;
            }
        }
        return json(DefaultResponse(200, true, '获取成功', $lists_news));
    }
    /**
    * @desc    按id查询附加信息
    * @date    2024/7/22
    * @author  zhangheng
    */
    public function AdvertisingInquiry($params = [])
    {
        $id = $params['id'] ?? "";
        if (!$id) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        //获取Facebook广告系列
        $ApiAdvLogic = new ApiAdvLogic();
        $info = $ApiAdvLogic->GetFacebookAdCampaigns($id);
        // halt($info);
        
        $lists_news['name'] = $info['name'] ?? "暂无";
        $lists_news['account_id'] = $info['account_id'] ?? "";
        $lists_news['info'] = "";
        if(!empty($lists_news['account_id'])){
            $advaccount = Db::name('advaccount')->where('advertiser_id',$lists_news['account_id'])->find();
            $lists_news['info'] = $advaccount['info'] ?? "";
        }
        return json(DefaultResponse(200, true, '获取成功', $lists_news));
    }
    
    /**
    * @desc    处理sku件数
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function NumberOfSKUsProcessed($children)
    {
        $groupedStatistics = [];
        foreach ($children as $item) {  
            // 使用explode来分割字符串，处理可能包含多个商品的情况  
            $items = explode(',', $item);  
            foreach ($items as $subItem) {  
                if (strpos($subItem, '-') !== false) {  
                    $spus = explode('-', $subItem);
                    $spu = $spus[0];
                    if(isset($groupedStatistics[$spu])){
                        $groupedStatistics[$spu] += 1;
                    }else{
                        $groupedStatistics[$spu] = 1;
                    }
                    if (strpos($subItem, '+') !== false) {  
                        //查询有几个加号
                        $plusCount = substr_count($subItem, '+'); 
                        $groupedStatistics[$spu] += (int)$plusCount;
                    }
                }
            }  
        }
        $childrens = [];  
        $total_count = 0; 
        foreach ($groupedStatistics as $k => $v) {  
            $new_arr = [  
                'spu' => $k,  
                'count' => $v  
            ];  
            $childrens[] = $new_arr;  
            $total_count += $v;  
        }
        $return = [  
            'childrens' => $childrens,  
            'count' => $total_count  
        ]; 
        return $return;
    }
    

    /**
    * @desc    识别成中文运营名称
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function tag_source($tag_source)
    {
        $ChannelLabelList = $this->arr_source();
        foreach ($ChannelLabelList as $k=>$v) {
            if($v['value'] == $tag_source){
                return $v['label'];
            }
        }
        return $tag_source;
    }

    /**
    * @desc    识别成中文运营名称
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function tag_campaign($tag_campaign)
    {
        $OperationLabelList = $this->arr_campaign();
        foreach ($OperationLabelList as $k=>$v) {
            if($v['value'] == $tag_campaign){
                return $v['label'];
            }
        }
        return $tag_campaign;
    }

    /**
    * @desc    arr_campaign
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function arr_source()
    {
        $data = [  
            ['value' => 'fb', 'label' => 'Facebook'],  
            ['value' => 'tt', 'label' => 'TikTok'],  
            ['value' => 'ggad', 'label' => 'google'],  
            ['value' => 'LabelIsEmpty', 'label' => '渠道标签为空'],
            ['value' => '直接访问', 'label' => '直接访问'],  
            ['value' => '待确认', 'label' => '待确认'],  
            ['value' => 'email', 'label' => 'email'],  
            ['value' => 'impact', 'label' => 'impact'],  
            ['value' => 'other', 'label' => 'other']
        ];
        return $data;
    }
    /**
    * @desc    arr_campaign
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function arr_campaign($type = 1)
    {
        $data = [  
            ['value' => 'lxf', 'label' => '李晓飞'],  
            ['value' => 'zx', 'label' => '张兴'],  
            ['value' => 'rjw', 'label' => '任洁文'],  
            ['value' => 'txl', 'label' => '陶小兰'],  
            ['value' => 'mf', 'label' => '马芳'],  
            // ['value' => 'khb', 'label' => '柯海波'],  
            // ['value' => 'hj', 'label' => '胡锦'],  
            // ['value' => 'hsw', 'label' => '侯思维'],  
            ['value' => 'bwh', 'label' => '白文华'],  
            ['value' => 'zby', 'label' => '章博语'],  
            // ['value' => 'wwj', 'label' => '伍文娟'],  
            // ['value' => 'ly', 'label' => '龙颖'],  
            // ['value' => 'hq', 'label' => '胡倩'],    
            // ['value' => 'xlh', 'label' => '许良海'],  
            // ['value' => 'zb', 'label' => '曾贝'],  
            ['value' => 'gjw', 'label' => '郭佳伟'],  
            ['value' => 'zjl', 'label' => '张金龙'],  
            ['value' => 'wd', 'label' => '王丹'],  
            // ['value' => 'my', 'label' => '马燕'],  
            // ['value' => 'tj', 'label' => '田军'],  
            ['value' => 'gjl', 'label' => '郭姜龙'],  
            ['value' => 'zsw', 'label' => '张松伟'],  
            ['value' => 'xjw', 'label' => '席佳雯'],  
            ['value' => 'zcc', 'label' => '张聪聪'],  
            ['value' => 'wb', 'label' => '魏冰'],  
            ['value' => 'lh', 'label' => '刘慧'],  
            ['value' => 'ld', 'label' => '刘丹'],  
            ['value' => 'mml', 'label' => '马明礼'],  
            ['value' => 'hgx', 'label' => '胡国霞'],  
            ['value' => 'dl', 'label' => '代亮'],  
            ['value' => 'LabelIsEmpty', 'label' => '运营标签为空'],  
        ];

        if($type == 2){
            $data2 = [  
                ['value' => 'ry', 'label' => '任莹'],  
                ['value' => 'wyl', 'label' => '吴玉龙'],  
                ['value' => 'lxy', 'label' => '李笑妍'],  
                ['value' => 'dqh', 'label' => '丁秋涵'],  
                // ['value' => 'gjl', 'label' => '郭纪伦'],  
                ['value' => 'ljx', 'label' => '李佳娴'],    
                ['value' => 'zcc', 'label' => '张聪聪'],  
                ['value' => 'wb', 'label' => '魏冰'],  
            ];
            $data = array_merge($data,$data2);
        }
        return $data;
    }
    

    /**
    * @desc    订单业绩--多店铺规则
    * @date    2024/7/22
    * @author  zhangheng
    */
    public function OrderAchievement($params = [])
    {
        $LastMonth = date('Y-m', strtotime('-32 day'));
        $date = $params['date'] ?? $LastMonth;
        $shop_id = $params['shop_id'] ?? 17;
        $where = [];

        // if (!$date) {
        $where[] = ['a.createtime', '>=', 1714492800];
        $where[] = ['a.createtime', '<=', 1717171199];
        // }
        if ($shop_id) {
            $where[] = ['a.shop_id', '=', $shop_id];
        }
        //汇率
        // $where[]  = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

        //汇率
        // $order_exchange = Db::name('order_exchange')
        //     ->where(['date' => $date])
        //     ->find();

        $lists = Db::name('order_source')
            ->field('
                a.created_at,
                a.name,
                a.financial_status,
                a.fulfillment_status,
                b.total_price,
                b.refund,
                b.freight,
                b.material,
                b.currency,
                a.tag_source,
                a.tag_campaign
            ')
            ->alias('a')
            ->join('qu_order_achievement b','b.order_id = a.order_id', 'left')
            ->where($where)
            ->limit(200)
            ->select()
            ->toArray();

        return json(DefaultResponse(200, true, '获取成功', $lists));
    }

    /**
    * @desc    订单业绩--多店铺规则
    * @date    2024/7/22
    * @author  zhangheng
    */
    public function OrderAchievementEdit($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $result = false;

        try {

            $result = true;
            
            if ($result) {
                return json(DefaultResponse(200, false, '更新成功!', null));
            }
            return json(DefaultResponse(201, false, '更新失败!', null));
        } catch (ValidateException $e) {
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            return json(DefaultResponse(201, false, '更新失败!', null));
        }
        return json(DefaultResponse(200, false, '更新成功!', null));
    }


    /**
     * @desc   导出表头数据
     * @author luckyXiong
     * @date   2024-08-08
     */
    public function export_set_heading()
    {
        return [
            'created_at'             => '日期',
            'name'                   => '订单号',
            'financial_status'       => '支付状态',
            'fulfillment_status'     => '物流状态',
            'old_total_price'        => '原销售额$',
            'refund_price'           => '退款',
            'total_price'            => '现销售额$',
            'freight'                => '账单物流费$',
            'estimate_freight'       => '预估物流费$(仅参考)',
            'material'               => '采购成本$',
            'dispute'                => '争议成本$',
            'dollar'                 => '美金汇率',
            'currency'               =>  '币种',
            'tag_source'             =>  'tag_source',
            'tag_campaign'           =>  'tag_campaign',
            'tags'                   =>  '原记录标签',
            'landing_site'           =>  'landing_site',
            'freight_status'         =>  '物流匹配状态',
            'material_status'        =>  '采购匹配状态',
            'disputeapi_type'        =>  '争议类型',
            'disputeapi_status'      =>  '争议状态',
            'skuquantity'            => '总件数',
            'sku'                    =>  'SKU',
            'firstVisit_source'  =>  'firstVisit_source',
            'firstVisit_campaign'  =>  'firstVisit_campaign',
            'lastVisit_source'  =>  'lastVisit_source',
            'lastVisit_campaign'  =>  'lastVisit_campaign',
            'last_source'  =>  'last_source',
            'last_campaign'  =>  'last_campaign',
            'first_source'  =>  'first_source',
            'first_campaign'  =>  'first_campaign',

        ];
    }


    /**
     * @desc   导出数据获取
     * @author luckyXiong
     * @date   2024-08-12
     */
    public function get_follow_list_export($params = [])
    {
        $params['limit']          =  2000;
        //导出三月数据处理;2024-08-03 分批次导出每次2000条
        $list  = (new OrderSourceModel())->pageList($params);
        $export_info = $list['data'];
        //数据处理;
        $title       = self::export_set_heading();
        $keys        = array_keys($title);
        $values      = array_pad([], count($keys), '');
        $intersect   = array_combine($keys, $values);
        $list = [];
        foreach($export_info as $row) {
            $tmp = array_intersect_key($row, $intersect);
            $arr =arraySortByKeys($tmp, $keys);
            $list[] = $arr;
        }
        return $list;
    }

    
    /**
    * @desc    编辑
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function wholePageModification($data = [])
    {
        $ids = $data['ids'];
        $tag_campaign = $data['tag_campaign'];

        if (!$ids) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        if (!$tag_campaign) {
            return json(DefaultResponse(201, false, '标签不能为空!', null));
        }
        $result = false;

        try {
            
            foreach ($ids as $value) {
                $updateData = [
                    'tag_campaign' => $tag_campaign,
                    'status' => 3,
                ];
                table('order_source')
                    ->where('id', $value)
                    ->update($updateData);
            }

            $result = true;
            
            if ($result) {
                return json(DefaultResponse(200, false, '更新成功!', null));
            }
            return json(DefaultResponse(201, false, '更新失败!', null));
        } catch (ValidateException $e) {
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            return json(DefaultResponse(201, false, '更新失败!', null));
        }
        return json(DefaultResponse(200, false, '更新成功!', null));
    }
    

}
